package com.demo.fragmentdemo

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    
    companion object {
        private const val TAG = "MainActivity_FragmentControl"
    }
    
    // Fragment状态跟踪
    private var fragment1: Fragment1? = null
    private var fragment3: Fragment3? = null
    
    // Fragment标签
    private val FRAGMENT1_TAG = "Fragment1"
    private val FRAGMENT3_TAG = "Fragment3"
    
    // 回退栈状态显示
    private lateinit var backstackStatusText: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // 初始化回退栈状态显示
        backstackStatusText = findViewById(R.id.tv_backstack_status)
        
        // 添加回退栈变化监听器
        supportFragmentManager.addOnBackStackChangedListener {
            updateBackstackStatus()
        }
        
        setupButtonListeners()
        updateBackstackStatus()

        // 注册 OnBackPressedCallback
        onBackPressedDispatcher.addCallback(this, object : androidx.activity.OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                handleBackPress()
            }
        })
        
        Log.d(TAG, "MainActivity 中的 supportFragmentManager: $supportFragmentManager")
    }
    
    private fun setupButtonListeners() {
        // Fragment1 控制按钮
        findViewById<Button>(R.id.btn_add_fragment1).setOnClickListener {
            addFragment1()
        }
        
        findViewById<Button>(R.id.btn_remove_fragment1).setOnClickListener {
            removeFragment1()
        }
        
        findViewById<Button>(R.id.btn_hide_fragment1).setOnClickListener {
            hideFragment1()
        }
        
        findViewById<Button>(R.id.btn_show_fragment1).setOnClickListener {
            showFragment1()
        }
        
        // Fragment3 控制按钮
        findViewById<Button>(R.id.btn_add_fragment3).setOnClickListener {
            addFragment3()
        }
        
        findViewById<Button>(R.id.btn_remove_fragment3).setOnClickListener {
            removeFragment3()
        }
        
        findViewById<Button>(R.id.btn_hide_fragment3).setOnClickListener {
            hideFragment3()
        }
        
        findViewById<Button>(R.id.btn_show_fragment3).setOnClickListener {
            showFragment3()
        }
        
        // Replace 按钮
        findViewById<Button>(R.id.btn_replace_with_fragment1).setOnClickListener {
            replaceWithFragment1()
        }
        
        findViewById<Button>(R.id.btn_replace_with_fragment3).setOnClickListener {
            replaceWithFragment3()
        }
        
        // 带回退栈的操作按钮
        findViewById<Button>(R.id.btn_add_fragment1_backstack).setOnClickListener {
            addFragment1WithBackstack()
        }
        
        findViewById<Button>(R.id.btn_remove_fragment1_backstack).setOnClickListener {
            removeFragment1WithBackstack()
        }
        
        findViewById<Button>(R.id.btn_hide_fragment1_backstack).setOnClickListener {
            hideFragment1WithBackstack()
        }
        
        findViewById<Button>(R.id.btn_show_fragment1_backstack).setOnClickListener {
            showFragment1WithBackstack()
        }
        
        findViewById<Button>(R.id.btn_add_fragment3_backstack).setOnClickListener {
            addFragment3WithBackstack()
        }
        
        findViewById<Button>(R.id.btn_remove_fragment3_backstack).setOnClickListener {
            removeFragment3WithBackstack()
        }
        
        findViewById<Button>(R.id.btn_hide_fragment3_backstack).setOnClickListener {
            hideFragment3WithBackstack()
        }
        
        findViewById<Button>(R.id.btn_show_fragment3_backstack).setOnClickListener {
            showFragment3WithBackstack()
        }
        
        findViewById<Button>(R.id.btn_replace_f1_backstack).setOnClickListener {
            replaceWithFragment1WithBackstack()
        }
        
        findViewById<Button>(R.id.btn_replace_f3_backstack).setOnClickListener {
            replaceWithFragment3WithBackstack()
        }
        
        // 回退栈管理按钮
        findViewById<Button>(R.id.btn_pop_backstack).setOnClickListener {
            popBackstack()
        }
        
        findViewById<Button>(R.id.btn_clear_backstack).setOnClickListener {
            clearBackstack()
        }
    }
    
    // Fragment1 操作方法
    private fun addFragment1() {
        if (fragment1 == null) {
            fragment1 = Fragment1.newInstance()
            supportFragmentManager.beginTransaction()
                .add(R.id.fragment_container, fragment1!!, FRAGMENT1_TAG)
                .commit()
            Log.d(TAG, "添加 Fragment1")
        } else {
            Toast.makeText(this, "Fragment1 已存在，无法重复添加", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment1 已存在，无法重复添加")
        }
    }
    
    private fun removeFragment1() {
        fragment1?.let { frag ->
            supportFragmentManager.beginTransaction()
                .remove(frag)
                .commit()
            fragment1 = null
            Log.d(TAG, "移除 Fragment1")
        } ?: run {
            Toast.makeText(this, "Fragment1 不存在，无法移除", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment1 不存在，无法移除")
        }
    }
    
    private fun hideFragment1() {
        fragment1?.let { frag ->
            supportFragmentManager.beginTransaction()
                .hide(frag)
                .commit()
            Log.d(TAG, "隐藏 Fragment1")
        } ?: run {
            Toast.makeText(this, "Fragment1 不存在，无法隐藏", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment1 不存在，无法隐藏")
        }
    }
    
    private fun showFragment1() {
        fragment1?.let { frag ->
            supportFragmentManager.beginTransaction()
                .show(frag)
                .commit()
            Log.d(TAG, "显示 Fragment1")
        } ?: run {
            Toast.makeText(this, "Fragment1 不存在，无法显示", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment1 不存在，无法显示")
        }
    }
    
    // Fragment3 操作方法
    private fun addFragment3() {
        if (fragment3 == null) {
            fragment3 = Fragment3.newInstance()
            supportFragmentManager.beginTransaction()
                .add(R.id.fragment_container, fragment3!!, FRAGMENT3_TAG)
                .commit()
            Log.d(TAG, "添加 Fragment3")
        } else {
            Toast.makeText(this, "Fragment3 已存在，无法重复添加", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment3 已存在，无法重复添加")
        }
    }
    
    private fun removeFragment3() {
        fragment3?.let { frag ->
            supportFragmentManager.beginTransaction()
                .remove(frag)
                .commit()
            fragment3 = null
            Log.d(TAG, "移除 Fragment3")
        } ?: run {
            Toast.makeText(this, "Fragment3 不存在，无法移除", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment3 不存在，无法移除")
        }
    }
    
    private fun hideFragment3() {
        fragment3?.let { frag ->
            supportFragmentManager.beginTransaction()
                .hide(frag)
                .commit()
            Log.d(TAG, "隐藏 Fragment3")
        } ?: run {
            Toast.makeText(this, "Fragment3 不存在，无法隐藏", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment3 不存在，无法隐藏")
        }
    }
    
    private fun showFragment3() {
        fragment3?.let { frag ->
            supportFragmentManager.beginTransaction()
                .show(frag)
                .commit()
            Log.d(TAG, "显示 Fragment3")
        } ?: run {
            Toast.makeText(this, "Fragment3 不存在，无法显示", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment3 不存在，无法显示")
        }
    }
    
    // Replace 操作方法
    private fun replaceWithFragment1() {
        fragment1 = Fragment1.newInstance()
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment1!!, FRAGMENT1_TAG)
            .commit()
        Log.d(TAG, "替换为 Fragment1")
    }
    
    private fun replaceWithFragment3() {
        fragment3 = Fragment3.newInstance()
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment3!!, FRAGMENT3_TAG)
            .commit()
        Log.d(TAG, "替换为 Fragment3")
    }
    
    // 带回退栈的Fragment操作方法
    private fun addFragment1WithBackstack() {
        fragment1 = Fragment1.newInstance()
        supportFragmentManager.beginTransaction()
            .add(R.id.fragment_container, fragment1!!, FRAGMENT1_TAG)
            .addToBackStack("Add_Fragment1")
            .commit()
        Log.d(TAG, "添加 Fragment1 到回退栈")
    }
    
    private fun removeFragment1WithBackstack() {
        fragment1?.let { frag ->
            supportFragmentManager.beginTransaction()
                .remove(frag)
                .addToBackStack("Remove_Fragment1")
                .commit()
            fragment1 = null
            Log.d(TAG, "移除 Fragment1 并添加到回退栈")
        } ?: run {
            Toast.makeText(this, "Fragment1 不存在，无法移除", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment1 不存在，无法移除")
        }
    }
    
    private fun hideFragment1WithBackstack() {
        fragment1?.let { frag ->
            supportFragmentManager.beginTransaction()
                .hide(frag)
                .addToBackStack("Hide_Fragment1")
                .commit()
            Log.d(TAG, "隐藏 Fragment1 并添加到回退栈")
        } ?: run {
            Toast.makeText(this, "Fragment1 不存在，无法隐藏", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment1 不存在，无法隐藏")
        }
    }
    
    private fun showFragment1WithBackstack() {
        fragment1?.let { frag ->
            supportFragmentManager.beginTransaction()
                .show(frag)
                .addToBackStack("Show_Fragment1")
                .commit()
            Log.d(TAG, "显示 Fragment1 并添加到回退栈")
        } ?: run {
            Toast.makeText(this, "Fragment1 不存在，无法显示", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment1 不存在，无法显示")
        }
    }
    
    private fun addFragment3WithBackstack() {
        fragment3 = Fragment3.newInstance()
        supportFragmentManager.beginTransaction()
            .add(R.id.fragment_container, fragment3!!, FRAGMENT3_TAG)
            .addToBackStack("Add_Fragment3")
            .commit()
        Log.d(TAG, "添加 Fragment3 到回退栈")
    }
    
    private fun removeFragment3WithBackstack() {
        fragment3?.let { frag ->
            supportFragmentManager.beginTransaction()
                .remove(frag)
                .addToBackStack("Remove_Fragment3")
                .commit()
            fragment3 = null
            Log.d(TAG, "移除 Fragment3 并添加到回退栈")
        } ?: run {
            Toast.makeText(this, "Fragment3 不存在，无法移除", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment3 不存在，无法移除")
        }
    }
    
    private fun hideFragment3WithBackstack() {
        fragment3?.let { frag ->
            supportFragmentManager.beginTransaction()
                .hide(frag)
                .addToBackStack("Hide_Fragment3")
                .commit()
            Log.d(TAG, "隐藏 Fragment3 并添加到回退栈")
        } ?: run {
            Toast.makeText(this, "Fragment3 不存在，无法隐藏", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment3 不存在，无法隐藏")
        }
    }
    
    private fun showFragment3WithBackstack() {
        fragment3?.let { frag ->
            supportFragmentManager.beginTransaction()
                .show(frag)
                .addToBackStack("Show_Fragment3")
                .commit()
            Log.d(TAG, "显示 Fragment3 并添加到回退栈")
        } ?: run {
            Toast.makeText(this, "Fragment3 不存在，无法显示", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "Fragment3 不存在，无法显示")
        }
    }
    
    private fun replaceWithFragment1WithBackstack() {
        fragment1 = Fragment1.newInstance()
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment1!!, FRAGMENT1_TAG)
            .addToBackStack("Replace_Fragment1")
            .commit()
        Log.d(TAG, "替换为 Fragment1 并添加到回退栈")
    }
    
    private fun replaceWithFragment3WithBackstack() {
        fragment3 = Fragment3.newInstance()
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment3!!, FRAGMENT3_TAG)
            .addToBackStack("Replace_Fragment3")
            .commit()
        Log.d(TAG, "替换为 Fragment3 并添加到回退栈")
    }
    
    // 回退栈管理方法
    private fun popBackstack() {
        if (supportFragmentManager.backStackEntryCount > 0) {
            supportFragmentManager.popBackStack()
            Log.d(TAG, "弹出回退栈")
        } else {
            Toast.makeText(this, "回退栈为空，无法弹出", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "回退栈为空，无法弹出")
        }
    }
    
    private fun clearBackstack() {
        val count = supportFragmentManager.backStackEntryCount
        if (count > 0) {
            supportFragmentManager.popBackStack(null, androidx.fragment.app.FragmentManager.POP_BACK_STACK_INCLUSIVE)
            Log.d(TAG, "清空回退栈，共清除了 $count 项")
        } else {
            Toast.makeText(this, "回退栈已为空", Toast.LENGTH_SHORT).show()
            Log.d(TAG, "回退栈已为空")
        }
    }
    
    // 更新回退栈状态显示
    private fun updateBackstackStatus() {
        val count = supportFragmentManager.backStackEntryCount
        backstackStatusText.text = "回退栈: $count 项"
        Log.d(TAG, "回退栈状态更新: $count 项")
    }

    /*
    * 通过返回键处理回退栈
     */
    private fun handleBackPress() {
        if (supportFragmentManager.backStackEntryCount > 0) {
            supportFragmentManager.popBackStack()
            updateBackstackStatus()
            Log.d(TAG, "通过返回键弹出回退栈")
        } else {
            finish() // 或者调用 isEnabled = false 然后重新调用 onBackPressedDispatcher.onBackPressed()
        }
    }
}